<template>
	<view class="uni-tab-bar">
		<view class="list">
			<block v-for="(newsItem, newsIndex) in currentList" :key="newsIndex" :id="newsItem.id">
				<view class="feed-list-item" hover-class="item-hover"  @click="goDetail(newsItem)">
					<view class="item-pic-v">
						<image v-if="newsItem.loaded" class="my-icon iconfont iconplayon play-icon" src="http://io.bukaa.cn/app/play_128px.png"/>
						<text  v-if="newsItem.loaded" class="time">{{newsItem.time}}</text>
						<!-- <image mode="widthFix" class="image avatar item-pic" :src="newsItem.pic" /> -->
						<image mode="widthFix" class="image avatar item-pic" :class="{lazy:!newsItem.show}" :data-index="newsIndex" @load="imgOnLoad" :src="newsItem.show?newsItem.pic:''" />
						<image mode="widthFix" class="image avatar item-pic placeholder" :class="{loaded:newsItem.loaded}" src="http://iph.href.lu/388x217?text=panpan" />
					</view>
					<view @click="goDetail(newsItem)">
						<text class="item-title">{{newsItem.title}}</text>
					</view>
					<view class="item-type-v">
						<text class="item-type">{{newsItem.summary}}</text>
					</view>
					<view class="item-author-v">
						<image @click="goUCenter(newsItem)" class="item-author-avatar" :src="newsItem.avatar" />
						<text  @click="goUCenter(newsItem)" class="item-author-name">
							{{newsItem.author}}
							<text style="color: #bbb;margin-left: 4upx;">{{newsItem.readCount}}查看 - {{newsItem.goodCount}}点赞</text>
						</text>
						<text class="item-author-date">{{newsItem.postdate}}</text>
					</view>
				</view>
			</block>
			<view v-if="true" class="feed-list-item" hover-class="item-hover" style="margin-bottom: 120upx;">
				<view class="feed-list-item-title-area">
					<text class="align-center-vertical" style="width: 100%;text-align: center;line-height: 120upx;color: #cbcbcb;">正在加载数据，请稍后...</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	let utils = require("@/common/util.js")

	export default {
		data() {
			return {
				showLoading: true,
				scrollLeft: 0,
				refreshing: false,
				refreshText: '下拉可以刷新',
				newsList: [],
				currentList: [],
				tabIndex: 'all',
				tabBars: [{
							id: 'all',
							name: '全部',
							title: 'all',
							icon: ''
						}],
				lastId: null,
				windowHeight: 0,
				navigationBarButtonTapTimes: 0,
			}
		},
		onLoad: function() {
			this.windowHeight = uni.getSystemInfoSync().windowHeight;
			// 初始化列表信息
			this.tabBars.forEach((tabBar) => {
				this.newsList.push({'all':{
					data: [],
					requestParams: {
						columnId: tabBar.id,
						size: 10,
						channel: 'weapp',
					},
				}});
			});
			this.getList();
		},
		onPullDownRefresh(event){
			this.refreshText = '正在刷新...';
			this.refreshing = true;
			this.getList(1);
		},
		onReachBottom(event){
			this.getList(2);
		},
		onPageScroll() {
			this.loadImg();
		},
		onNavigationBarButtonTap() {
			if(plus && plus.nativeUI && this.navigationBarButtonTapTimes <1){
				this.navigationBarButtonTapTimes ++;
				//plus.nativeUI.toast("再次点击将回到顶部");
				return;
			}
			this.navigationBarButtonTapTimes = 0;
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
		},
		methods: {
			getList(action = 1) {
				var that = this;
				let activeTab = that.newsList[that.tabIndex] || {requestParams:{per_page: 10, b_id: 0}};
				if (action === 1) {
					activeTab.requestParams.b_id = 0;
				}
				that.showLoading = true;
				uni.request({
					url: 'https://bukaa.cn/api-cms/36kr/videos',
					data: activeTab.requestParams,
					success: (result) => {
						var data = result.data;
						if (data.status === 'ok') {
							var feeds = data.data.data.items;
							if (feeds && feeds.length > 0) { // 如果有返回数据
								const data = feeds.map((news) => {
									activeTab.requestParams.b_id = news.id;
									return {
										id: news.id,
										postdate: news.published_at,
										title: news.title,
										pic: news.cover,
										avatar: news.user.avatar_url || 'http://io.bukaa.cn/touxiang-girl.png',
										author: news.user.name,
										summary: news.summary,
										goodCount: news.counters.like,
										readCount: news.counters.favorite,
										comment_count: news.counters.comment,
										time: that.secToTime(news.duration),
										post_id: news.id,
										url: news.url_1152 || news.url,
										show: false,
										loaded: false,
										authorId: news.authorId
									};
								});
								if (action === 1) {
									activeTab.data = data;
									that.refreshing = false;
									setTimeout(() => {
										that.loadImg();
									}, 100)
								} else {
									data.forEach((news) => {
										activeTab.data.push(news);
									});
								}
								that.currentList = activeTab.data;
								that.newsList[that.tabIndex] = activeTab;
							} else {
								//self.setData({ loading: false });
							}
						}
					},
					complete:()=>{
						that.showLoading = false;
						uni.stopPullDownRefresh();
					}
				});
			},
			  /**
			 * 时间秒数格式化
			 * @param s 时间戳（单位：秒）
			 * @returns {*} 格式化后的时分秒
			 */
			secToTime(s) {
				var t = "";
				if(s > -1){
					var hour = Math.floor(s/3600);
					var min = Math.floor(s/60) % 60;
					var sec = s % 60;
					if(hour < 10 && hour > 0) {
						t = '0'+ hour + ":";
					} else if(hour >= 10) {
						t = hour + ":";
					}

					if(min < 10){t += "0";}
					t += min + " : ";
					if(sec < 10){t += "0";}
					t += sec.toFixed(0);
				}
				return t;
			},
			goDetail(detail) {
				uni.navigateTo({
					url: '/pages/hot-v/detail?query=' + encodeURIComponent(JSON.stringify(detail))
				});
			},
			goUCenter1(detail){
				uni.navigateTo({
					url: '/pages/article/user?query=' + encodeURIComponent(JSON.stringify(detail))
				});
			},
			loadMore() {
				this.getList(2);
			},
			async changeTab(event) {
				let index = event.detail.current;
				if (this.isClickChange) {
					this.tabIndex = index;
					this.isClickChange = false;
					return;
				}
				let tabBar = await this.getElSize('tab-bar');
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;

				for (let i = 0; i < index; i++) {
					let result = await this.getElSize(this.tabBars[i].title);
					width += result.width;
				}
				var nowWidth = 0;
				let winWidth = uni.getSystemInfoSync().windowWidth,
					nowElement = await this.getElSize(this.tabBars[index].title);
					nowWidth = nowElement.width;
				if (width + nowWidth - tabBarScrollLeft > winWidth) {
					this.scrollLeft = width + nowWidth - winWidth;
				}
				if (width < tabBarScrollLeft) {
					this.scrollLeft = width;
				}
				
				this.isClickChange = false;
				
				
				this.tabIndex = this.tabBars[index].id;

				// 首次切换后加载数据
				this.currentList = this.newsList[index] ? this.newsList[index].data : [];
				
				const activeTab = this.newsList[this.tabIndex];
				if (!activeTab || activeTab.data.length === 0) {
					this.getList();
				}
			},
			getNodeSize(node) {
				return new Promise((resolve, reject) => {
					dom.getComponentRect(node, (result) => {
						resolve(result.size);
					});
				});
			},
			onRefresh(event) {
				this.refreshText = '正在刷新...';
				this.refreshing = true;
				this.getList();
			},
			getElSize(id) { //得到元素的size
				return new Promise((res, rej) => {
					uni.createSelectorQuery().select('#' + id).fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			async tapTab(tab) { //点击tab-bar
				var index = tab.id;
				this.currentList = this.newsList[index] ? this.newsList[index].data : [];
				if (this.tabIndex === index) {
					return false;
				} else {
					let tabBar = await this.getElSize('tab-bar'),
						tabBarScrollLeft = tabBar.scrollLeft; //点击的时候记录并设置scrollLeft
					this.scrollLeft = tabBarScrollLeft;
					this.isClickChange = true;
					this.tabIndex = index;
					// 首次切换后加载数据
					const activeTab = this.newsList[this.tabIndex];
					if (!activeTab || activeTab.data.length === 0) {
						this.getList();
					}
				}
			},
			loadImg() {
				var that = this;
				uni.createSelectorQuery().selectAll('.lazy').boundingClientRect((images) => {
					images.forEach((image, index) => {
						if (image.top <= that.windowHeight) {
							that.currentList[image.dataset.index].show = true;
						}
					})
				}).exec()
			},
			imgOnLoad(e) {
				this.currentList[e.target.dataset.index].loaded = true
			}
		}
	}
</script>
<style>
	@import url("../../static/css/list.css");
	.list{
		width: 90%;
	}
	.feed-list-item{
		border-radius: 10px;
	}
	.item-pic-v{
		width: 100%;
		height: 400upx;
		align-items: left;
		transition: opacity .3s;
		display: inline-block;
		float: left;
		position: relative;
	}
	.play-icon{
		width: 60px;
		height: 60px;
		position: absolute;
		z-index: 99999;
		left: 42%;
		top: 38%;
	}
	.time{
		position: absolute;
		z-index: 1;
		right: 0;
		bottom: 6upx;
		background: rgba(0,0,0,.5);
		border-radius: .5px .5px 2px .5px;
		color: #fff;
		font-size: 20upx;
		padding: 6upx;
	}
	.item-pic{
		float: left;
		width: 100%;
		height: auto;
		position: absolute;
	}
	.item-title{
		padding: 10upx;
		font-size: 14px;
		font-weight: 600;
		color: #333;
		vertical-align: middle;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.item-type-v{
		height: 30upx;
		padding: 10upx;
	}
	.item-type{
		line-height: 40upx;
		float: left;
		font-size: 12px;
		color: #bbb;
	}
	.item-info-v{
		height: 30upx;
		padding: 10upx;
	}
	.item-info{
		line-height: 40upx;
		float: left;
		font-size: 12px;
		color: #bbb;
	}
	.item-author-v{
		height: 60upx;
		padding: 10upx;
		margin-bottom: 10upx;
	}
	.item-author-avatar{
		width: 60upx;
		height: 60upx;
		border-radius: 50%;
		float: left;
	}
	.item-author-name{
		line-height: 60upx;
		float: left;
		font-size: 12px;
		margin-left: 10upx;
	}
	.item-author-date{
		line-height: 60upx;
		float: right;
		font-size: 12px;
		color: #bbb;
		margin-bottom: 20upx;
	}
</style>
